import 'package:flutter/material.dart';
import 'bitmap.dart';
import 'canvas_edit.dart';
import 'curtain_light_model.dart';

/// 画布设置
/// 移动[move], 填充[filling], 涂抹[smear], 擦除[erase], 设置[settings]
enum CanvasType { move, filling, smear, erase, settings }

class CurtainMatrixView extends StatefulWidget {
  CurtainMatrixView({
    Key? key,
    required this.amount,
    required this.directionType,
    required this.displayX,
    required this.displayY,
    required this.bitmap,
    required this.color,
    required this.canvasType,
    this.onChangedBitmap,
  })  : assert(amount > 0),
        super(key: key);

  final int amount;
  final DiyDeviceDirectionType directionType;
  final int displayX;
  final int displayY;
  final Bitmap bitmap;
  final Color color;
  final CanvasType canvasType;
  final ValueChanged<Bitmap>? onChangedBitmap;

  @override
  State<StatefulWidget> createState() => CurtainMatrixViewState();
}

class CurtainMatrixViewState extends State<CurtainMatrixView> {
  late Bitmap bitmap = widget.bitmap;
  late Color _color = widget.color;
  late CanvasType _canvasType = widget.canvasType;

  double x = -1, y = -1;

  int hideCountX = 0, hideCountY = 0;
  bool isTouch = false;

  late int tempX, tempY;
  late int tempHideX, tempHideY;
  late double tempPosX, tempPosY;

  late Size sizeBox;

  @override
  void didUpdateWidget(covariant CurtainMatrixView oldWidget) {
    if (oldWidget.bitmap != widget.bitmap ||
        oldWidget.color != widget.color ||
        oldWidget.canvasType != widget.canvasType) {
      setState(() {
        bitmap = widget.bitmap;
        _color = widget.color;
        _canvasType = widget.canvasType;
      });
    }
    super.didUpdateWidget(oldWidget);
  }

  @override
  Widget build(BuildContext context) {
    return LayoutBuilder(
      builder: (_, constraints) {
        final size = Size(constraints.maxWidth, constraints.maxHeight);
        sizeBox = size;
        return ClipRect(
          child: Container(
            width: size.width,
            height: size.height,
            child: CanvasEdit(
              amount: widget.amount,
              directionType: widget.directionType,
              sizeBox: size,
              displayX: widget.displayX,
              displayY: widget.displayY,
              color: _color,
              canvasType: _canvasType,
              bitmap: bitmap,
              onCallbackBitmap: (value) {
                widget.onChangedBitmap?.call(value);
              },
            ),
          ),
        );
      },
    );
  }
}
